<template>
  <div class="chat-container">
    <!-- <div class="chat-header">
      <div class="header-content">
        <el-button v-if="hasMessages" class="clear-button" @click="handleClearChat" size="small">
          <el-icon><Delete /></el-icon>
          <span>清除对话</span>
        </el-button>
      </div>
    </div> -->

    <div ref="chatContainerRef" class="messages-container beautify-scroll-def">
      <!-- Chat messages -->
        <MessageItem 
          v-for="(message, index) in chatMessages" 
          :key="index" 
          :message="message" 
        />

      <!-- Loading indicator -->
      <div v-if="isLoading && hasUserInput" class="loading-container">
        <div class="loading-indicator">
          <span>正在处理您的请求...</span>
        </div>
      </div>

      <!-- Error message -->
      <div v-if="error" class="error-message">
        <el-alert
          title="出错了"
          type="error"
          :description="error"
          show-icon
          :closable="false"
        />
      </div>
    </div>

    <div class="input-container">
      <MessageInput 
        :disabled="isLoading" 
        @send="handleSendMessage" 
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick, watch } from 'vue';
import { useChatStore } from '@/stores/chat.ts';
import MessageInput from '@/components/MessageInput.vue';
import MessageItem from '@/components/MessageItem.vue';
import { Delete, ChatRound, ChatDotRound } from '@element-plus/icons-vue';
import { aiApi } from "@/api";
import ai from "@/assets/ai.json";
console.log(ai,'ai-------------');

const chatStore = useChatStore();
const chatMessages = computed(() => chatStore.messages);
const isLoading = computed(() => chatStore.isLoading);
const error = computed(() => chatStore.error);
const chatContainerRef = ref<HTMLElement | null>(null);

const hasMessages = computed(() => chatMessages.value.length > 0);
const hasUserInput = computed(() => chatMessages.value.some(m => m.role === 'user'));
const hasAssistantMessage = computed(() => chatMessages.value.some(m => m.role === 'assistant'));

const scrollToBottom = async () => {
  await nextTick();
  if (chatContainerRef.value) {
    const container = chatContainerRef.value;
    container.scrollTop = container.scrollHeight;
  }
};
function getFirst4ChineseChars(str) {
    // 匹配汉字正则：[\u4e00-\u9fa5]
    const chineseChars = str.match(/[\u4e00-\u9fa5]/g) || [];
    return chineseChars.slice(0, 5).join('');
}
const handleSendMessage = async (message: string) => {
  console.log(message,'message--');
  const str1 = message.replace(/\s/g, '')
  const aiObj = ai.find(item => str1.includes(getFirst4ChineseChars(item.问)))
  if (str1 && aiObj) {
    console.log(aiObj.答);
    chatStore.sendMessageClick(str1)
    setTimeout(()=>{
      chatStore.receiveMessage(aiObj.答, false, true)
    }, 500)
    return
  }
  if (message.startsWith("@")) {
    const str = message.slice(1).trim()
      chatStore.sendMessageClick(str)
      const res = await aiApi({ message: str, chatMessages: chatMessages.value })
      if (res.success) {
        chatStore.receiveMessage(res.data)
      }
      return
    }
  if (!message.trim()) return;
  
  try {
    await chatStore.sendMessage(message);
    await scrollToBottom();
  } catch (err) {
    console.error('发送消息失败:', err);
  }
};

const handleClearChat = () => {
  chatStore.clearMessages();
};

const useExamplePrompt = (prompt: string) => {
  handleSendMessage(prompt);
};

onMounted(() => {
  // 加载页面时滚动到底部
  scrollToBottom();
});

// 监听消息列表变化，自动滚动到底部
watch(
  chatMessages,
  () => {
    scrollToBottom();
  },
  { deep: true }
);
</script>

<style scoped lang="scss">

.chat-container {
  display: flex;
  flex-direction: column;
  // height: calc(100% - 12px);
  max-width: 100%;
  margin: 0 auto;
  width: 100%;
  background-color: rgba(16, 36, 58, 0.4);
  height: 100%;
}

.chat-header {
  background-color: white;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  z-index: 10;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  max-width: 1000px;
  margin: 0 auto;
  width: 100%;
}

.logo-area {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-icon {
  width: 28px;
  height: 28px;
}

.app-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--neutral-800);
  margin: 0;
}

.clear-button {
  color: var(--neutral-600);
  background-color: transparent;
  border: 1px solid var(--neutral-300);
  display: flex;
  align-items: center;
  gap: 4px;
}

.clear-button:hover {
  color: var(--error-color);
  border-color: var(--error-color);
  background-color: #FEF2F2;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  // padding: 1.5rem 1rem;
  display: flex;
  flex-direction: column;
  // gap: 1.5rem;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
  padding: 0 1rem;
  margin-top: -4rem;
}

.welcome-message {
  margin-bottom: 2.5rem;
  max-width: 600px;
}

.welcome-message h2 {
  color: var(--primary-color);
  margin-bottom: 1rem;
  font-size: 1.75rem;
}

.welcome-message p {
  font-size: 1.1rem;
  line-height: 1.6;
  color: var(--neutral-600);
}

.examples-container {
  width: 100%;
  max-width: 700px;
}

.examples-container h3 {
  margin-bottom: 1rem;
  font-weight: 600;
  color: var(--neutral-700);
  font-size: 1.1rem;
}

.example-prompts {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1rem;
}

.example-prompt {
  padding: 1rem;
  background-color: white;
  border: 1px solid var(--neutral-200);
  border-radius: var(--radius-lg);
  cursor: pointer;
  transition: all 0.2s ease;
  line-height: 1.5;
  color: var(--neutral-700);
  display: flex;
  align-items: flex-start;
  gap: 0.75rem;
  box-shadow: var(--shadow-sm);
}

.example-prompt .el-icon {
  color: var(--primary-color);
  margin-top: 0.125rem;
}

.example-prompt:hover {
  background-color: var(--primary-bg);
  border-color: var(--primary-light);
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
}

.loading-container {
  display: flex;
  justify-content: center;
  margin: 1rem 0;
}

.loading-indicator {
  padding: 0.5rem 1rem;
  background-color: white;
  border-radius: 2rem;
  color: var(--primary-color);
  font-size: 0.875rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  box-shadow: var(--shadow-sm);
}

.error-message {
  margin: 1rem 0;
}

.input-container {
  padding: 1rem;
  background-color: rgba(2, 167, 240, 0.2);
  // border-top: 1px solid var(--neutral-200);
  box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.05);
  border-radius: 8px;
}

/* 媒体查询适配不同屏幕尺寸 */
@media (max-width: 768px) {
  .chat-container {
    padding: 0;
  }
  
  .example-prompts {
    grid-template-columns: 1fr;
  }
  
  .messages-container {
    // padding: 1rem 0.75rem;
    padding: 8px 6px;
  }
}
</style> 